﻿using Repository.Impl;
using SqlSugar;
using System.Linq.Expressions;

namespace Repository
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
    {
        private SqlSugarScope _SqlSugar;

        public ISqlSugarClient db => _SqlSugar;

        public BaseRepository(IUnitOfWork unitOfWork)
        {
            _SqlSugar = unitOfWork.GetDbClient();
        }


        #region Async

        #region Other
        /// <summary>
        /// 判断是否存在记录
        /// </summary>
        /// <param name="where">实体类</param>
        /// <returns></returns>
        public async Task<bool> Exists(Expression<Func<TEntity, bool>> where = null)
        {
            return await _SqlSugar.Queryable<TEntity>().AnyAsync(where);
        }

        /// <summary>
        /// 统计数据数量
        /// </summary>
        /// <param name="where">实体类</param>
        /// <returns></returns>
        public async Task<int> QueryCount(Expression<Func<TEntity, bool>> where = null)
        {
            return await _SqlSugar.Queryable<TEntity>().WhereIF(where != null, where).CountAsync();
        }
        #endregion

        #region Add
        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<int> Add(TEntity entity)
        {
            return await _SqlSugar.Insertable(entity).ExecuteCommandAsync();
        }

        /// <summary>
        /// 批量写入实体数据
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public async Task<bool> AddList(List<TEntity> entities)
        {
            return await _SqlSugar.Insertable(entities).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 插入或更新
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public async Task<bool> AddOrUpdate(TEntity entities, string UpIgnore = "AddTime")
        {
            var x = db.Storageable(entities).ToStorage();
            var insert = await x.AsInsertable.ExecuteCommandAsync();
            var update = await x.AsUpdateable.IgnoreColumns(UpIgnore).ExecuteCommandAsync();
            if (insert > 0 || update > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 插入或更新列表
        /// </summary>
        /// <param name="list">实体类集合</param>
        /// <returns></returns>
        public async Task<bool> AddOrUpdateList(List<TEntity> list, string UpIgnore = "AddTime")
        {
            var x = db.Storageable(list).ToStorage();
            var insert = await x.AsInsertable.ExecuteCommandAsync();
            var update = await x.AsUpdateable.IgnoreColumns(UpIgnore).ExecuteCommandAsync();
            if (insert > 0 || update > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region Delete

        /// <summary>
        /// 根据实体删除一条数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> Delete(TEntity entity)
        {
            return await _SqlSugar.Deleteable(entity).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 逻辑删除实体
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> DeleteLogic(TEntity entity, string logicKey = "IsDelete")
        {
            return await _SqlSugar.Deleteable(entity).IsLogic().ExecuteCommandAsync(logicKey) > 0;
        }

        /// <summary>
        /// 删除指定ID的数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task<bool> DeleteById(object id)
        {
            return await _SqlSugar.Deleteable<TEntity>(id).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdLogic(object id, string logicKey = "IsDelete")
        {
            return await _SqlSugar.Deleteable<TEntity>(id).IsLogic().ExecuteCommandAsync(logicKey) > 0;
        }

        /// <summary>
        /// 删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIds(object[] ids)
        {
            return await _SqlSugar.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdsLogic(object[] ids, string logicKey = "IsDelete")
        {
            return await _SqlSugar.Deleteable<TEntity>().In(ids).IsLogic().ExecuteCommandAsync(logicKey) > 0;
        }
        #endregion

        #region Update
        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> Update(TEntity entity)
        {
            //这种方式会以主键为条件
            return await _SqlSugar.Updateable(entity).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 批量更新实体数据
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public async Task<bool> UpdateList(List<TEntity> entities, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = "")
        {
            IUpdateable<TEntity> up = _SqlSugar.Updateable(entities);
            if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
            {
                up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
            }
            if (lstColumns != null && lstColumns.Count > 0)
            {
                up = up.UpdateColumns(lstColumns.ToArray());
            }
            if (!string.IsNullOrEmpty(strWhere))
            {
                up = up.Where(strWhere);
            }
            return await up.ExecuteCommandHasChangeAsync();
        }

        public async Task<bool> Update(TEntity entity, string strWhere)
        {
            return await _SqlSugar.Updateable(entity).Where(strWhere).ExecuteCommandHasChangeAsync();
        }

        public async Task<bool> Update(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = "")
        {
            IUpdateable<TEntity> up = _SqlSugar.Updateable(entity);
            if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
            {
                up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
            }
            if (lstColumns != null && lstColumns.Count > 0)
            {
                up = up.UpdateColumns(lstColumns.ToArray());
            }
            if (!string.IsNullOrEmpty(strWhere))
            {
                up = up.Where(strWhere);
            }
            return await up.ExecuteCommandHasChangeAsync();
        }
        #endregion

        #region Query
        /// <summary>
        /// 根据ID查询单条数据（异步）   
        /// </summary>
        /// <param name="objId"></param>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public async Task<TEntity> QueryByID(object objId, Expression<Func<TEntity, bool>> whereExpression = null)
        {
            return await _SqlSugar.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).InSingleAsync(objId);
        }

        /// <summary>
        /// 根据多个ID查询列表数据（异步）        
        /// </summary>
        /// <param name="lstIds">id列表（必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]），如果是联合主键，请使用Where条件</param>
        /// <returns>数据实体列表</returns>
        public async Task<List<TEntity>> QueryByIDs(object[] lstIds, Expression<Func<TEntity, bool>> whereExpression = null)
        {
            return await _SqlSugar.Queryable<TEntity>().In(lstIds).WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }

        /// <summary>
        /// 查询所有数据（异步）  
        /// </summary>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> QueryAll()
        {
            return await _SqlSugar.Queryable<TEntity>().ToListAsync();
        }

        /// <summary>
        /// 查询数据列表 （异步）       
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(string strWhere)
        {
            return await _SqlSugar.Queryable<TEntity>().WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
        }

        /// <summary>
        /// 查询数据列表（异步）    
        /// </summary>
        /// <param name="whereExpression">whereExpression</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
        {
            return await _SqlSugar.Queryable<TEntity>().Where(whereExpression).ToListAsync();
        }

        /// <summary>
        /// 根据表达式主键查询单条数据（异步）
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public async Task<TEntity> QuerySingle(Expression<Func<TEntity, bool>> whereExpression)
        {
            return await _SqlSugar.Queryable<TEntity>().SingleAsync(whereExpression);
        }

        /// <summary>
        /// 查询一个列表（异步）
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="orderByExpression"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
        {
            return await _SqlSugar.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }

        /// <summary>
        /// 查询一个列表（异步）        
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(string strWhere, string strOrderByFileds)
        {
            return await _SqlSugar.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
        }

        /// <summary>
        /// 查询前N条数据（异步）      
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int intTop, string strOrderByFileds)
        {
            return await _SqlSugar.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).Take(intTop).ToListAsync();
        }

        /// <summary>
        /// 分页查询sql（异步）       
        /// </summary>
        /// <param name="sql">条件表达式</param>
        /// <param name="intPageIndex">页码（1开始）</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="TotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> QueryPage(string sql, SugarParameter sugarParameter, RefAsync<int> TotalCount, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
        {
            return await _SqlSugar.SqlQueryable<TEntity>(sql).AddParameters(new SugarParameter[] { sugarParameter })
            .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
            .ToPageListAsync(intPageIndex, intPageSize, TotalCount);
        }

        /// <summary>
        /// 分页查询（异步）        
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intPageIndex">页码（1开始）</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="TotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, RefAsync<int> TotalCount, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
        {
            return await _SqlSugar.Queryable<TEntity>()
            .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
            .WhereIF(whereExpression != null, whereExpression).ToPageListAsync(intPageIndex, intPageSize, TotalCount);
        }

        /// <summary>
        /// sql查询返回实体集合（异步）     
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public async Task<List<TEntity>> SqlQuery(string sql)
        {
            return await _SqlSugar.Ado.SqlQueryAsync<TEntity>(sql);
        }

        /// <summary>
        /// 表达式查询第一条记录（异步）
        /// </summary>
        /// <param name="whereExpression">表达式</param>
        /// <returns></returns>
        public async Task<TEntity> QueryFirst(Expression<Func<TEntity, bool>> whereExpression)
        {
            return await _SqlSugar.Queryable<TEntity>().FirstAsync(whereExpression);
        }

        /// <summary>
        /// sql查询第一条记录（异步）
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public async Task<TEntity> SqlQuerySingle(string sql)
        {
            return await _SqlSugar.Ado.SqlQuerySingleAsync<TEntity>(sql);
        }
        #endregion

        #endregion


        #region Sync

        #region Other
        /// <summary>
        /// 判断是否存在记录(同步)
        /// </summary>
        /// <param name="where">实体类</param>
        /// <returns></returns>
        public bool ExistsSync(Expression<Func<TEntity, bool>> where = null)
        {
            return _SqlSugar.Queryable<TEntity>().Any(where);
        }

        /// <summary>
        /// 统计数据数量（同步）
        /// </summary>
        /// <param name="where">实体类</param>
        /// <returns></returns>
        public int QueryCountSync(Expression<Func<TEntity, bool>> where = null)
        {
            return _SqlSugar.Queryable<TEntity>().WhereIF(where != null, where).Count();
        }

        #endregion

        #region Add
        /// <summary>
        /// 写入实体数据（同步）
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public int AddSync(TEntity entity)
        {
            return _SqlSugar.Insertable(entity).ExecuteCommand();
        }

        /// <summary>
        /// 批量写入实体数据（同步）
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public bool AddListSync(List<TEntity> entities)
        {
            return _SqlSugar.Insertable(entities).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 插入或更新（同步）
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public bool AddOrUpdateSync(TEntity entities, string UpIgnore = "AddTime")
        {
            var x = db.Storageable(entities).ToStorage();
            var insert = x.AsInsertable.ExecuteCommand();
            var update = x.AsUpdateable.IgnoreColumns(UpIgnore).ExecuteCommand();
            if (insert > 0 || update > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 插入或更新列表
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public bool AddOrUpdateListSync(List<TEntity> entities, string UpIgnore = "AddTime")
        {
            var x = db.Storageable(entities).ToStorage();
            var insert = x.AsInsertable.ExecuteCommand();
            var update = x.AsUpdateable.IgnoreColumns(UpIgnore).ExecuteCommand();
            if (insert > 0 || update > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region Delete

        /// <summary>
        /// 根据实体删除一条数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool DeleteSync(TEntity entity)
        {
            return _SqlSugar.Deleteable(entity).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 逻辑删除实体
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool DeleteLogicSync(TEntity entity, string logicKey = "IsDelete")
        {
            return _SqlSugar.Deleteable(entity).IsLogic().ExecuteCommand(logicKey) > 0;
        }

        /// <summary>
        /// 删除指定ID的数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public bool DeleteByIdSync(object id)
        {
            return _SqlSugar.Deleteable<TEntity>(id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 逻辑删除
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public bool DeleteByIdLogicSync(object id, string logicKey = "IsDelete")
        {
            return _SqlSugar.Deleteable<TEntity>(id).IsLogic().ExecuteCommand(logicKey) > 0;
        }

        /// <summary>
        /// 删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public bool DeleteByIdsSync(object[] ids)
        {
            return _SqlSugar.Deleteable<TEntity>().In(ids).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public bool DeleteByIdsLogicSync(object[] ids, string logicKey = "IsDelete")
        {
            return _SqlSugar.Deleteable<TEntity>().In(ids).IsLogic().ExecuteCommand(logicKey) > 0;
        }
        #endregion

        #region Update
        /// <summary>
        /// 更新实体数据(同步)
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public bool UpdateSync(TEntity entity)
        {
            //这种方式会以主键为条件
            return _SqlSugar.Updateable(entity).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 批量更新实体数据(同步)
        /// </summary>
        /// <param name="entities">实体类集合</param>
        /// <returns></returns>
        public bool UpdateListSync(List<TEntity> entities, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = "")
        {
            IUpdateable<TEntity> up = _SqlSugar.Updateable(entities);
            if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
            {
                up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
            }
            if (lstColumns != null && lstColumns.Count > 0)
            {
                up = up.UpdateColumns(lstColumns.ToArray());
            }
            if (!string.IsNullOrEmpty(strWhere))
            {
                up = up.Where(strWhere);
            }
            return up.ExecuteCommandHasChange();
        }

        public bool UpdateSync(TEntity entity, string strWhere)
        {
            return _SqlSugar.Updateable(entity).Where(strWhere).ExecuteCommandHasChange();
        }

        public bool UpdateSync(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = "")
        {
            IUpdateable<TEntity> up = _SqlSugar.Updateable(entity);
            if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
            {
                up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
            }
            if (lstColumns != null && lstColumns.Count > 0)
            {
                up = up.UpdateColumns(lstColumns.ToArray());
            }
            if (!string.IsNullOrEmpty(strWhere))
            {
                up = up.Where(strWhere);
            }
            return up.ExecuteCommandHasChange();
        }
        #endregion

        #region Query
        /// <summary>
        /// 根据ID查询单条数据（同步）    
        /// </summary>
        /// <param name="objId"></param>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public TEntity QueryByIDSync(object objId, Expression<Func<TEntity, bool>> whereExpression = null)
        {
            return _SqlSugar.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).InSingle(objId);
        }

        /// <summary>
        /// 根据ID查询数据（同步）          
        /// </summary>
        /// <param name="lstIds">id列表（必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]），如果是联合主键，请使用Where条件</param>
        /// <returns>数据实体列表</returns>
        public List<TEntity> QueryByIDsSync(object[] lstIds, Expression<Func<TEntity, bool>> whereExpression = null)
        {
            return _SqlSugar.Queryable<TEntity>().In(lstIds).WhereIF(whereExpression != null, whereExpression).ToList();
        }

        /// <summary>
        /// 查询所有数据（同步）        
        /// </summary>
        /// <returns>数据列表</returns>
        public List<TEntity> QueryAllSync()
        {
            return _SqlSugar.Queryable<TEntity>().ToList();
        }

        /// <summary>
        /// 查询数据列表（同步）         
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QuerySync(string strWhere)
        {
            return _SqlSugar.Queryable<TEntity>().WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToList();
        }

        /// <summary>
        /// 查询数据列表（同步）         
        /// </summary>
        /// <param name="whereExpression">whereExpression</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QuerySync(Expression<Func<TEntity, bool>> whereExpression)
        {
            return _SqlSugar.Queryable<TEntity>().Where(whereExpression).ToList();
        }

        /// <summary>
        /// 查询数据列表（同步）
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public TEntity QuerySingleSync(Expression<Func<TEntity, bool>> whereExpression)
        {
            return _SqlSugar.Queryable<TEntity>().Single(whereExpression);
        }

        /// <summary>
        /// 查询一个列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="orderByExpression"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public List<TEntity> QuerySync(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
        {
            return _SqlSugar.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToList();
        }

        /// <summary>
        /// 查询一个列表        
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QuerySync(string strWhere, string strOrderByFileds)
        {
            return _SqlSugar.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToList();
        }

        /// <summary>
        /// 查询前N条数据        
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QuerySync(Expression<Func<TEntity, bool>> whereExpression, int intTop, string strOrderByFileds)
        {
            return _SqlSugar.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).Take(intTop).ToList();
        }

        /// <summary>
        /// 分页查询sql       
        /// </summary>
        /// <param name="sql">条件表达式</param>
        /// <param name="intPageIndex">页码（1开始）</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="TotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QueryPageSync(string sql, SugarParameter sugarParameter, int TotalCount, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
        {
            return _SqlSugar.SqlQueryable<TEntity>(sql).AddParameters(new SugarParameter[] { sugarParameter })
            .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
            .ToPageList(intPageIndex, intPageSize, ref TotalCount);
        }

        /// <summary>
        /// 分页查询（同步）        
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intPageIndex">页码（1开始）</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="TotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段，如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public List<TEntity> QueryPageSync(Expression<Func<TEntity, bool>> whereExpression, ref int TotalCount, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null)
        {
            return _SqlSugar.Queryable<TEntity>()
            .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
            .WhereIF(whereExpression != null, whereExpression).ToPageList(intPageIndex, intPageSize, ref TotalCount);
        }

        /// <summary>
        /// 查询返回实体集合（同步）    
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public List<TEntity> SqlQuerySync(string sql)
        {
            return _SqlSugar.Ado.SqlQuery<TEntity>(sql);
        }

        /// <summary>
        /// 表达式查询第一条记录
        /// </summary>
        /// <param name="whereExpression">表达式</param>
        /// <returns></returns>
        public TEntity QueryFirstSync(Expression<Func<TEntity, bool>> whereExpression)
        {
            return _SqlSugar.Queryable<TEntity>().First(whereExpression);
        }

        /// <summary>
        /// 查询第一条记录
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public TEntity SqlQuerySingleSync(string sql)
        {
            return _SqlSugar.Ado.SqlQuerySingle<TEntity>(sql);
        }
        #endregion

        #endregion


    }

}
